package com.jinzhi.jzweb.controller;


import cn.afterturn.easypoi.excel.ExcelExportUtil;
import cn.afterturn.easypoi.excel.entity.ExportParams;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.jinzhi.common.annotation.Log;
import com.jinzhi.common.base.BaseController;
import com.jinzhi.common.utils.EhCacheUtil;
import com.jinzhi.common.utils.Result;
import com.jinzhi.jzweb.domain.*;
import com.jinzhi.jzweb.pojo.ErroeDownVo;
import com.jinzhi.jzweb.pojo.moduleConfig.PaperVo;
import com.jinzhi.jzweb.service.*;
import com.jinzhi.jzweb.service.moduleConfig.ExaminationQuestionsComService;
import com.jinzhi.jzweb.utils.EasyPoiUtil;
import com.jinzhi.sys.domain.UserDO;
import com.jinzhi.sys.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 *
 * <pre>
 * 考试试卷
 * </pre>
 * <small> 2020-02-24 21:00:12 | lance</small>
 */
@Controller
@RequestMapping("/jzweb/examinationPaper")
public class ExaminationPaperController extends BaseController {
	@Autowired
	private ExaminationPaperService examinationPaperService;
	@Autowired
	private UserService userService;
	@Autowired
	private ExaminationBatchComService examinationBatchService;
	@Autowired
	private ExaminationQuestionsService examinationQuestionsService;

	@Autowired
	private ExaminationPaperComService examinationPaperComService;

	@Autowired
	private ExaminationQuestionsComService examinationQuestionsComService;

	@GetMapping()
	String ExaminationPaper(){
		return "jzweb/examinationPaper/examinationPaper";
	}

	@ResponseBody
	@GetMapping("/list")
	public Result<Page<ExaminationPaperDO>> list(ExaminationPaperDO examinationPaperDTO){
		Wrapper<ExaminationPaperDO> wrapper = new EntityWrapper<ExaminationPaperDO>().orderBy("type", false).orderBy("sort",true);
		if (examinationPaperDTO.getState() != null){
			wrapper.eq("state",examinationPaperDTO.getState());
		}
		if (examinationPaperDTO.getNumbers() != null){
			wrapper.like("numbers",examinationPaperDTO.getNumbers());
		}
		if (examinationPaperDTO.getName() != null){
			wrapper.like("name",examinationPaperDTO.getName());
		}
		if (examinationPaperDTO.getCbatchId() != null){
			wrapper.eq("ebatch_id",examinationPaperDTO.getCbatchId());
		}
		if (StringUtils.isNotBlank(examinationPaperDTO.getEbatchName())){
			Wrapper<ExaminationBatchComDO> exWrapper = new EntityWrapper<ExaminationBatchComDO>().like("name",examinationPaperDTO.getEbatchName());
			List<ExaminationBatchComDO>  examinationBatchDOS = examinationBatchService.selectList(exWrapper);
			String str = "";
			for (ExaminationBatchComDO examinationBatchDO : examinationBatchDOS){
				str = str + examinationBatchDO.getId() + ",";
			}
			wrapper.and();
			if(StringUtils.isNotBlank(str)){
				wrapper.in("ebatch_id",str.substring(0,str.length()-1));
			}else{
				wrapper.eq("ebatch_id",null);
			}
		}

		Page<ExaminationPaperDO> page = examinationPaperService.selectPage(getPage(ExaminationPaperDO.class), wrapper);
		List list = new ArrayList();
		for (int i = 0; i < page.getRecords().size(); i++) {
			ExaminationPaperDO obj = (ExaminationPaperDO) page.getRecords().get(i);
			if (obj.getCreaterId() != null){
				UserDO userDO = userService.selectById(obj.getCreaterId());
				if (userDO != null) {
					obj.setCreaterName(userDO.getUsername());
				}
			}
			if (obj.getCheckerId() != null){
				UserDO userDO = userService.selectById(obj.getCheckerId());
				if (userDO != null) {
					obj.setCheckerName(userDO.getUsername());
				}
			}
			if (obj.getEbatchId() != null){
				ExaminationBatchComDO examinationBatchDO = examinationBatchService.selectById(obj.getEbatchId());
				if (examinationBatchDO != null) {
					obj.setEbatchName(examinationBatchDO.getName());
				}
			}
			//查询试卷题目数量
			EntityWrapper<ExaminationQuestionsDO> wrapper1 = new EntityWrapper<ExaminationQuestionsDO>();
			wrapper1.eq("epaper_id",obj.getId());
			wrapper1.eq("state",0);
			int i1 = examinationQuestionsService.selectCount(wrapper1);
			obj.setNumQuestions(i1);
			list.add(obj);
		}
		page.setRecords(list);
		return Result.ok(page);
	}

	@GetMapping("/add")
	String add(){
		return "jzweb/examinationPaper/add";
	}

	@GetMapping("/edit/{id}")
	String edit(@PathVariable("id") Long id,Model model){
		ExaminationPaperDO examinationPaper = examinationPaperService.selectById(id);
		model.addAttribute("examinationPaper", examinationPaper);
		return "jzweb/examinationPaper/edit";
	}

	@Log("添加考试试卷")
	@ResponseBody
	@PostMapping("/save")
	public Result<String> save( ExaminationPaperDO examinationPaper){
		examinationPaper.setCreaterId(this.getUserId());
		examinationPaperService.insert(examinationPaper);
		return Result.ok();
	}

	@Log("修改考试试卷")
	@ResponseBody
	@RequestMapping("/update")
	public Result<String>  update( ExaminationPaperDO examinationPaper){
		boolean update = examinationPaperService.updateById(examinationPaper);
		return update ? Result.ok() : Result.fail();
	}

	@Log("清除试卷缓存")
	@ResponseBody
	@RequestMapping("/clearCache")
	public Result<String>  clearCache(Long id){
		ExaminationPaperDO epaper = examinationPaperService.selectById(id);
		ExaminationBatchComDO examinationBatchDO = examinationBatchService.selectById(epaper.getEbatchId());
		if(examinationBatchDO==null){
			return Result.fail();
		}
		EhCacheUtil.remove("examinationPaperDO"+examinationBatchDO.getId());
		return Result.ok("清除成功");
	}

	@Log("删除考试试卷")
	@PostMapping( "/remove")
	@ResponseBody
	public Result<String>  remove( Long id){

		ExaminationPaperDO examinationPaperDO = examinationPaperService.selectById(id);
		if(examinationPaperDO.getEbatchId() != null){

			//删除考试试题
			List<ExaminationQuestionsDO> examinationQuestionsDOS = examinationQuestionsService.findByKv("epaper_id",id);
			if(examinationQuestionsDOS != null &&examinationQuestionsDOS.size() > 0){
				List<Long> ids = new ArrayList<>();
				for(int j=0;j<examinationQuestionsDOS.size();j++){
					ids.add(examinationQuestionsDOS.get(j).getId());
				}
				examinationQuestionsService.deleteBatchIds(ids);
			}
			//删除考试试卷
			examinationPaperService.deleteById(id);

			//判断当前考试批次是否还存在试卷，不存在则修改批次状态为 `1已通过`
			List<ExaminationPaperDO> examinationPaperDOS = examinationPaperService.selectList(new EntityWrapper<ExaminationPaperDO>().eq("ebatch_id", examinationPaperDO.getEbatchId()));
			if(examinationPaperDOS==null || examinationPaperDOS.isEmpty()){
				ExaminationBatchComDO examinationBatchComDO = new ExaminationBatchComDO();
				examinationBatchComDO.setId(examinationPaperDO.getEbatchId());
				examinationBatchComDO.setState(1);
				examinationBatchService.updateById(examinationBatchComDO);
			}
		}

		return Result.ok();
	}

	@Log("批量删除考试试卷")
	@PostMapping( "/batchRemove")
	@ResponseBody
	public Result<String>  remove(@RequestParam("ids[]") Long[] ids){
		if(ids != null && ids.length > 0){
			for(int i=0;i<ids.length;i++){
				ExaminationPaperDO examinationPaperDO = examinationPaperService.selectById(ids[i]);
				if(examinationPaperDO.getEbatchId() != null){

					//删除考试试题
					List<ExaminationQuestionsDO> examinationQuestionsDOS = examinationQuestionsService.findByKv("epaper_id",ids[i]);
					if(examinationQuestionsDOS != null &&examinationQuestionsDOS.size() > 0){
						List<Long> idS = new ArrayList<>();
						for(int j=0;j<examinationQuestionsDOS.size();j++){
							idS.add(examinationQuestionsDOS.get(j).getId());
						}
						examinationQuestionsService.deleteBatchIds(idS);
					}
					//删除考试试卷
					examinationPaperService.deleteById(ids[i]);

					//判断当前考试批次是否还存在试卷，不存在则修改批次状态为 `1已通过`
					List<ExaminationPaperDO> examinationPaperDOS = examinationPaperService.selectList(new EntityWrapper<ExaminationPaperDO>().eq("ebatch_id", examinationPaperDO.getEbatchId()));
					if(examinationPaperDOS==null || examinationPaperDOS.isEmpty()){
						ExaminationBatchComDO examinationBatchComDO = new ExaminationBatchComDO();
						examinationBatchComDO.setId(examinationPaperDO.getEbatchId());
						examinationBatchComDO.setState(1);
						examinationBatchService.updateById(examinationBatchComDO);
					}
				}
			}
		}

		return Result.ok();
	}

	@Log("审核")
	@PostMapping( "/review")
	@ResponseBody
	public Result<String>  review(@RequestParam("ids[]") Long[] ids,Integer state,String remark){
		if (state.equals(2) || state.equals(1)) {
			int i = 0;
			for (Long id : ids) {
				ExaminationPaperDO examinationPaperDO = examinationPaperService.selectById(id);
				if(examinationPaperDO != null){
					examinationPaperDO.setState(state);
					examinationPaperDO.setCheckerId(this.getUserId());
					examinationPaperDO.setCheckerDate(new Date());
					if(state.equals(2)){
						examinationPaperDO.setRemark(remark);//未通过，添加备注
					}else{
						examinationPaperDO.setRemark("");//审核通过，清空备注
					}
					boolean b = examinationPaperService.updateById(examinationPaperDO);
					if (b) {
						i++;
					} else {
						break;
					}
				}
			}
			if (i == ids.length) {
				return Result.build(0,"已成功审核：" + i + "条数据");
			} else {
				return Result.fail("审核状态修改失败！");
			}
		} else {
			return Result.fail("审核状态修改失败！");
		}
	}


	/**
	 * 下载导入模板
	 *
	 * @param response
	 */
	@RequestMapping("/downloadImportTemplate")
	@ResponseBody
	public void downloadImportTemplate(HttpServletResponse response) {
		List<PaperVo> list = new LinkedList<>();
		//导出操作
		EasyPoiUtil.exportExcel(list, "试卷信息导入模板", "试卷信息导入模板", PaperVo.class, "试卷信息导入模板", response);
	}


	/**
	 * 导入试卷信息
	 * @param file
	 * @param cprofileId 竞赛批次id
	 * @param paperName 试卷名称
	 * @return
	 */
	@Log("试卷信息导入")
	@PostMapping("/import")
	@ResponseBody
	@Transactional
	public Result<?> importExcel(@RequestParam("file") MultipartFile file, String cprofileId, String paperName,Integer type){

		return examinationPaperComService.importExcel(file,cprofileId,this.getUserId(),paperName,type);

	}



	/**
	 * 查询试卷祥请
	 * @param examinationPaperComDO
	 * @return
	 */
	@PostMapping("/questionsComList")
	@ResponseBody
	@Transactional
	public Result<?> questionsComList(@RequestBody ExaminationPaperComDO examinationPaperComDO){

		return examinationPaperComService.queryQuestionsComList(examinationPaperComDO);

	}

	/**
	 * 新增试卷题目
	 * @param examinationQuestionsComDO
	 * @return
	 */
	@PostMapping("/addQuestions")
	@ResponseBody
	@Transactional
	public Result<?> addQuestions(@RequestBody ExaminationQuestionsComDO examinationQuestionsComDO){

		return examinationQuestionsComService.addQuestions(examinationQuestionsComDO);

	}


	/**
	 * 删除试卷题目
	 * @param examinationQuestionsComDO
	 * @return
	 */
	@PostMapping("/deleteQuestions")
	@ResponseBody
	@Transactional
	public Result<?> deleteQuestions(@RequestBody ExaminationQuestionsComDO examinationQuestionsComDO){

		return examinationQuestionsComService.deleteQuestions(examinationQuestionsComDO);

	}

	//导入试卷页面
	@GetMapping("/addPaper")
	String importPage(){
		return "jzweb/examinationPaper/addPaper";
	}



	/**
	 * 导入试卷祥请列表
	 * @param examinationPaperComDO
	 * @return
	 */
	@PostMapping("/questionList")
	@ResponseBody
	@Transactional
	public Result<?> questionList(@RequestBody ExaminationPaperComDO examinationPaperComDO){

		return examinationPaperComService.questionList(examinationPaperComDO);

	}


	/**
	 * 导出错误信息
	 *
	 * @param request
	 * @param response
	 * @throws Exception
	 * @author kl
	 */
	@Log("导出错误信息")
	@GetMapping("/importError")
	@ResponseBody
	@Transactional
	public void download(HttpServletRequest request, HttpServletResponse response) throws Exception {
		// 告诉浏览器用什么软件可以打开此文件
		response.setHeader("content-Type", "application/vnd.ms-excel");
		// 下载文件的默认名称
		response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("试卷导入错误信息", "UTF-8") + ".xls");
		//编码
		response.setCharacterEncoding("UTF-8");
		String jsonArray = EhCacheUtil.get("paper" + this.getUserId()).toString();
		JSONArray arrayList = JSONArray.parseArray(jsonArray);
		//转换为目标对象list
		List<ErroeDownVo> groupList = JSONObject.parseArray(arrayList.toJSONString(), ErroeDownVo.class);
		Workbook workbook = ExcelExportUtil.exportExcel(new ExportParams(), ErroeDownVo.class, groupList);
		workbook.write(response.getOutputStream());
	}


	//导入试卷编辑页面
	@GetMapping("/paperEdit/{id}")
	String paperEdit(@PathVariable("id") Long id,Model model){
		ExaminationQuestionsDO examinationQuestions = examinationQuestionsService.selectById(id);
		model.addAttribute("examinationPaper", examinationQuestions);
		return "jzweb/examinationPaper/paperEdit";
	}

	@Log("删除考试试题")
	@PostMapping( "/removeQuestion")
	@ResponseBody
	public Result<String>  removeQuestion(Long id){
		examinationQuestionsService.deleteById(id);
		return Result.ok();
	}


	@Log("指定试卷")
	@PostMapping( "/specifyPaper")
	@ResponseBody
	@RequiresPermissions("jzweb:examinationPaper:specifyPaper")
	public Result<?> specifyPaper(Long id){

		return examinationPaperComService.specifyPaper(id);
	}

}
